package com.yupi.yupao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.yupao.common.BaseContext;
import com.yupi.yupao.common.BaseResponse;
import com.yupi.yupao.common.ErrorCode;
import com.yupi.yupao.common.ResultUtils;
import com.yupi.yupao.exception.BusinessException;
import com.yupi.yupao.model.domain.Team;
import com.yupi.yupao.model.domain.User;
import com.yupi.yupao.model.domain.UserTeam;
import com.yupi.yupao.model.domain.dto.TeamQuery;
import com.yupi.yupao.model.domain.request.*;
import com.yupi.yupao.model.vo.TeamUserMapVO;
import com.yupi.yupao.model.vo.TeamUserVO;
import com.yupi.yupao.service.TeamService;
import com.yupi.yupao.service.UserService;
import com.yupi.yupao.service.UserTeamService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.prefs.BackingStoreException;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author: Peter
 * @Date: 2024-05-07-11:24
 * @Description: Pe
 */
@RestController
@RequestMapping("/team")
@Api(tags = "组队模块")
@CrossOrigin(origins = "http://127.0.0.1:5173/",allowCredentials = "true")
@Slf4j
public class TeamController {
    @Resource
    private TeamService teamService;
    @Resource
    private UserService userService;
    @Resource
    private UserTeamService userTeamService;

    @ApiOperation("创建队伍")
    @PostMapping("create")

    public BaseResponse<Long> createTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest httpServletRequest){
        if(teamAddRequest==null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
//        boolean isSave = teamService.save(team);

        Long userId = BaseContext.getCurrentId();
        User userInfo = userService.getById(userId);
        Team team = new Team();
        BeanUtils.copyProperties(teamAddRequest,team);
        Long teamId = teamService.createTeam(team, userInfo);

        return ResultUtils.success(teamId);
    }
    @ApiOperation("删除队伍")
    @DeleteMapping("delete")
    public BaseResponse<Boolean> deleteTeam(long id,HttpServletRequest request){
        if(id<=0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Long userId = BaseContext.getCurrentId();
        User userInfo = userService.getById(userId);
        boolean isDel = teamService.deleteTeam(id,userInfo);
        if(!isDel){
            throw  new BusinessException(ErrorCode.SYSTEM_ERROR,"删除失败");
        }
        return ResultUtils.success(true);
    }
    @ApiOperation("修改队伍")
    @PostMapping("update")
    public BaseResponse<Boolean> updateTeam(@RequestBody TeamUpdateRequest teamUpdateRequest,HttpServletRequest request){
        if(teamUpdateRequest==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
//        User loginUser = userService.getLoginUser(request);
        Long userId = BaseContext.getCurrentId();
        User userInfo = userService.getById(userId);
        boolean isUpdate = teamService.updateTeam(teamUpdateRequest,userInfo);
        if(!isUpdate){
            throw  new BusinessException(ErrorCode.SYSTEM_ERROR,"修改失败");
        }
        return ResultUtils.success(true);
    }
    @ApiOperation("查找队伍")
    @PostMapping("list")
    public BaseResponse<TeamUserMapVO> TeamList(@RequestBody TeamQuery teamQuery, HttpServletRequest request){
        if(teamQuery==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long userId = BaseContext.getCurrentId();
        User userInfo = userService.getById(userId);
        boolean isAdmin = userService.isAdmin(userInfo);
//        Team team = new Team();
//        BeanUtils.copyProperties(team,teamQuery);
//        QueryWrapper<Team> queryWrapper = new QueryWrapper<>(team);
        TeamUserMapVO teamList = teamService.listTeams(teamQuery,isAdmin);
        return ResultUtils.success(teamList);


    }
    @ApiOperation("查找队伍（分页）")
    @PostMapping("list/page")
    public BaseResponse<IPage<Team>> TeamListPage(@RequestBody PageRequest pageRequest){
        if(pageRequest==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
        queryWrapper.and(qw -> qw.gt("expireTime", new Date()).or().isNull("expireTime"));
        IPage<Team> page = teamService.page(new Page(pageRequest.getPageNum(),pageRequest.getPageSize()), queryWrapper);
        return ResultUtils.success(page);


    }
    @ApiOperation("加入队伍")
    @PostMapping("join")
    public BaseResponse<Boolean> JoinTeam(@RequestBody TeamJoinRequest teamJoinRequest,HttpServletRequest request){
        if(teamJoinRequest==null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }

        Long userId = BaseContext.getCurrentId();
        User userInfo = userService.getById(userId);
        boolean isJoin= teamService.JoinTeam(teamJoinRequest,userInfo);
        return ResultUtils.success(isJoin);
    }
    @ApiOperation("退出队伍")
    @PostMapping("quit")
    public BaseResponse<Boolean> QuitTeam(@RequestBody TeamQuitRequest teamQuitRequest, HttpServletRequest request){
        if(teamQuitRequest==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long userId = BaseContext.getCurrentId();
        User userInfo = userService.getById(userId);

        boolean isQuit= teamService.quitTeam(teamQuitRequest,userInfo);
        return ResultUtils.success(isQuit);



    }
    @ApiOperation("当前用户已创建的队伍")
    @PostMapping("list/my/create")
    public BaseResponse<TeamUserMapVO> TeamMyCreate(TeamQuery teamQuery, HttpServletRequest request){
        if(teamQuery==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long userId = BaseContext.getCurrentId();
        User userInfo = userService.getById(userId);
        boolean isAdmin = userService.isAdmin(userInfo);
//        Team team = new Team();
//        BeanUtils.copyProperties(team,teamQuery);
//        QueryWrapper<Team> queryWrapper = new QueryWrapper<>(team);

        teamQuery.setUserId(userId);
        TeamUserMapVO teamList = teamService.listTeams(teamQuery,isAdmin);
        return ResultUtils.success(teamList);


    }
    @ApiOperation("当前用户已加入的队伍")
    @PostMapping("list/hasJoin")
    public BaseResponse<TeamUserMapVO> TeamHasJoin(TeamQuery teamQuery, HttpServletRequest request){
        if(teamQuery==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long userId = BaseContext.getCurrentId();
        User userInfo = userService.getById(userId);
        boolean isAdmin = userService.isAdmin(userInfo);

        QueryWrapper<UserTeam> wrapper = new QueryWrapper<>();
        wrapper.eq("userId",userId);
        List<UserTeam> userTeamList = userTeamService.list(wrapper);

        //分组
        Map<Long, List<UserTeam>> listMap = userTeamList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));

        ArrayList<Long> idList = new ArrayList<>(listMap.keySet());
        teamQuery.setIdList(idList);


//        Team team = new Team();
//        BeanUtils.copyProperties(team,teamQuery);
//        QueryWrapper<Team> queryWrapper = new QueryWrapper<>(team);
        TeamUserMapVO teamList = teamService.listTeams(teamQuery,isAdmin);
        Stream<TeamUserVO> userVOStream = teamList.getTeamUserVOList().stream().filter(item -> !item.getUserId() .equals(userId) );
        List<TeamUserVO> userVOList = userVOStream.collect(Collectors.toList());
        teamList.setTeamUserVOList(userVOList);
        teamList.setTotalPage(Long.valueOf(userVOList.size()) );
        return ResultUtils.success(teamList);


    }
    @GetMapping("/hasJoin")
    public BaseResponse<List<Team>> hasJoin(){

        Long userId = BaseContext.getCurrentId();

        QueryWrapper<UserTeam> wrapper = new QueryWrapper<>();
        wrapper.eq("userId",userId);
        List<UserTeam> userTeamList = userTeamService.list(wrapper);
        List<Long> idList = new ArrayList<>();
        if(userTeamList.size()<=0 ){
            throw new BusinessException(ErrorCode.NULL_TEAM,"队伍为空");
        }
        userTeamList.stream().forEach(item->{
            idList.add(item.getTeamId());
        });
        log.info("idList");
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id",idList);
        List<Team> teamList = teamService.list(queryWrapper);
        log.info("teamList"+teamList);
        Stream<Team> teamStream = teamList.stream().filter(item -> !item.getUserId().equals(userId) );
        List<Team> collect = teamStream.collect(Collectors.toList());
        return ResultUtils.success(collect);
    }
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public BaseResponse fileUpload(MultipartFile file){

        return ResultUtils.success(teamService.fileUpload(file));
    }
    @GetMapping("/policy")
    public BaseResponse<Map<String,String>> getOSSPolicy(){
        return ResultUtils.success(teamService.getOSSPolicy());
    }
    @PostMapping("/policy")
    public BaseResponse<String> postOSSPolicy(){
        return null;
    }

}
